package com.mz.mattress.admin.service.impl;

import com.mz.mattress.admin.common.FailMessage;
import com.mz.mattress.admin.mapper.MemberMapper;
import com.mz.mattress.admin.service.SmsService;
import com.mz.mattress.api.aliyun.SmsUtil;
import com.mz.mattress.api.redis.RedisKeys;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.enums.SmsEnum;
import com.mz.mattress.api.util.RegexUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Result sendVerifyCode(String mobile, SmsEnum smsEnum) {
        String code = String.valueOf(ThreadLocalRandom.current().nextInt(8999) + 1000);
        Map<String, String> param = new HashMap<>(5);
        param.put("code", code);

        Result result = SmsUtil.send(mobile, smsEnum, param);
        if (result.isSuccess()) {
            redisTemplate.opsForValue().set(RedisKeys.getSmsCodeKey(smsEnum, mobile), code, 30, TimeUnit.MINUTES);
        }

        return result;
    }

    @Override
    public Result sendSmsCode(String mobile, SmsEnum smsEnum) {
        if (!RegexUtil.isMobileExact(mobile)) {
            return Result.fail("手机号格式错误！");
        }
        return sendVerifyCode(mobile, smsEnum);
    }

    @Override
    public Result validVerifyCode(String mobile, String code, SmsEnum smsEnum) {

        // 检查手机号是否真实
        if (!RegexUtil.isMobileExact(mobile)) {
            log.error("register_mobile_fail,mobile={}", mobile);
            return Result.fail(FailMessage.INVALID_MOBILE);
        }

        Object object = redisTemplate.opsForValue().get(RedisKeys.getSmsMobileKey(mobile));
        if (object == null) {
            return Result.fail(FailMessage.BAD_ARGUMENT);
        }
        // 检查短信验证码是否正确
        if (!object.toString().equals(code)) {
            return Result.fail(FailMessage.WRONG_CODE_ARGUMENT);
        }

        return Result.ok();
    }

}
